package top.codestudy.ui;

import groovy.util.Node;
import groovy.util.XmlParser;
import groovy.xml.QName;
import org.xml.sax.SAXException;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;

public class SwitchCaseDialog extends JDialog{
    private JPanel viewParent;
    private JButton btnConfirm;
    private JCheckBox includeSwitch;
    private JTable table1;
    private JButton selectAll;
    private JButton selectNone;

    private String xmlText;

    public SwitchCaseDialog(){
        setContentPane(viewParent);
        setTitle("SwitchCase");
        this.setAlwaysOnTop(true);
        // 当用点击 ‘enter’ 时调用btnConfirm的点击事件
        getRootPane().setDefaultButton(btnConfirm);

        btnConfirm.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                boolean ischeck = includeSwitch.isSelected();
                StringBuilder javaCode = new StringBuilder();
                MyTableModel model = (MyTableModel)table1.getModel();
                if (ischeck){
                    javaCode.append("switch(v.getId()) {\n");
                }
                for(int i=0;i<model.getRowCount();i++){
                    boolean b = (boolean)model.getValueAt(i,2);
                    if (b){
                        javaCode.append("case R.id."+model.getValueAt(i,1).toString()+":\n");
                        javaCode.append("break;\n");
                    }
                }
                if (ischeck){
                    javaCode.append("}\n");
                }
                Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
                Transferable tText = new StringSelection(javaCode.toString());
                clip.setContents(tText, null);
                SwitchCaseDialog.this.dispose();
            }
        });

        selectAll.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String text = "";
                MyTableModel model = (MyTableModel)table1.getModel();
                for(int i=0;i<model.getRowCount();i++){
                    model.setValueAt(true,i,2);
                }

            }
        });

        selectNone.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String text = "";
                MyTableModel model = (MyTableModel)table1.getModel();
                for(int i=0;i<model.getRowCount();i++){
                    model.setValueAt(false,i,2);
                }

            }
        });
    }

    private void createUIComponents() {

    }

    public void init(String text){
        this.xmlText = text;
        table1.setModel(new MyTableModel(text));
    }

    class MyTableModel extends AbstractTableModel {
        private String[] columnNames = {"Class",
                "Id",
                "Check"};

        private String xmlText;
        private List<Mydata> data = new ArrayList<>();
        public MyTableModel(String text){
            super();
            xmlText = text;
            Node node = null;
            Map<String,String> map = new HashMap();
            //定义命名空间
            map.put("android","http://schemas.android.com/apk/res/android");
            System.out.println("includeSwitch : " + includeSwitch.isSelected());
            try {

                XmlParser xmlParser = new XmlParser();
                //xmlParser.startPrefixMapping("android","http://schemas.android.com/apk/res/android");
                node = xmlParser.parseText(text);
                /**
                 * 1.搜索所有的包含 id 属性的 节点
                 * 2.保存此id，以及对应的类名
                 * 3.初始化table 中的 data 数据
                 */

                Map<QName,String> attributes = node.attributes();
                //调试用的
//                System.out.println(node);
//                for (Map.Entry<QName,String> e: attributes.entrySet()){
//                    System.out.println(e.getKey().getQualifiedName()+ " === " + e.getValue());
//                }
                bianliNode(node);
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
                System.out.println("ParserConfigurationException");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("IOException");
            } catch (SAXException e) {
                e.printStackTrace();
                System.out.println("SAXException");
            }
        }

        private void bianliNode(Node node) {
            if (node == null){
                return;
            }
            Map<QName,String> attributes = node.attributes();
            for (Map.Entry<QName,String> e: attributes.entrySet()){
                try{
                    if ("android:id".equals(e.getKey().getQualifiedName())){
                        Mydata mydata = new Mydata(node.name().toString(), e.getValue().split("/")[1]);
                        data.add(mydata);
                    }
                }catch (ClassCastException ex){

                }
            }
            List<Node> children = node.children();
            if (children == null){
                return;
            }
            for(int i=0;i<children.size();i++){
                bianliNode(children.get(i));
            }
        }

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.size();
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            if (col == 0){
                return data.get(row).className;
            }
            if (col == 1){
                return data.get(row).id;
            }
            if (col == 2){
                return data.get(row).isCheck;
            }
            return null;
        }

        /*
         * JTable uses this method to determine the default renderer/
         * editor for each cell.  If we didn't implement this method,
         * then the last column would contain text ("true"/"false"),
         * rather than a check box.
         */
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        /*
         * Don't need to implement this method unless your table's
         * editable.
         */
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            if (col < 2) {
                return false;
            } else {
                return true;
            }
        }

        /*
         * Don't need to implement this method unless your table's
         * data can change.
         */
        public void setValueAt(Object value, int row, int col) {

            if (col == 0){
                 data.get(row).className = (String)value;
            }
            if (col == 1){
                 data.get(row).id = (String)value;
            }
            if (col == 2){
                data.get(row).isCheck = (boolean)value;
            }
            fireTableCellUpdated(row, col);

        }


    }

    public static class Mydata {
        String className;
        String id;
        Boolean isCheck = true;

        public Mydata(String className,String id){
            this.className = className;
            this.id = id;
        }
    }

}
